$(function(){
    //$.sme.cbk.ajaxUserMenuItem();
    //$.sme.init.ajaxMenuItemHistory();
    $.sme.init.registerAjaxCallbacks();
    $.sme.init.justifyPainator();
    $.sme.init.initWidgets();
    $.sme.init.justifyTables();
    $.sme.init.justifyLinks();
    $.sme.init.justifyInputs();
    $.sme.init.tooltips();
    $.sme.init.dialogs();
    $.sme.init.flashMessage();
});

// Tomato self defind functions, callbacks, etc
;(function($){
$.sme = {};
// Define the global namespace, $.sme
$.extend($.sme, {
    k: function(){},       // Empty function
    cache: {},                // Cached elements, and data
    cbk: {},                    // Module action callbacks
    data: {},                  // Data holder
    fn: {},                       // Utility functions
    init: {},                    // Page initialize functions
    inits: [],                   // Holder all names of initialize functions
    option: {},              // Options holder, for ajax, animations
    status: {},              // Options holder, for ajax, animations
    timer: {},                 // Timer holder
    url: {}                       // Ajax request url prefixes
});

// Define some ajax request url constructors
$.sme.url.base = 'http://localhost/tests/sme/';
$.extend($.sme.url, {
    user: function(action){ return $.sme.url.base+'users/'+action+'/'; },
    group: function(action){ return $.sme.url.base+'groups/'+action+'/'; },
    post: function(action){ return $.sme.url.base+'posts/'+action+'/'; },
    post_term: function(action){ return $.sme.url.base+'post_terms/'+action+'/'; },
    post_attachment: function(action){ return $.sme.url.base+'post_attachments/'+action+'/'; },
    student: function(action){ return $.sme.url.base+'students/'+action+'/'; },
    company: function(action){ return $.sme.url.base+'companies/'+action+'/'; },
    company_industry: function(action){ return $.sme.url.base+'company_industries/'+action+'/'; },
    company_location: function(action){ return $.sme.url.base+'company_locations/'+action+'/'; },
    company_type: function(action){ return $.sme.url.base+'company_types/'+action+'/'; }
});

// Webpage initialize functions
$.extend($.sme.init, {
    // Ajax loading for page contents when click meta links
    ajaxMenuItemHistory: function(){
        $.historyInit($.sme.cbk.ajaxMenuItemLoad);
        $('a.user_menu_item').click(function(event){
            event.preventDefault();
            $.sme.data.menu = $(this);
            var hash = this.href;
            hash = hash.replace(/^.*#/, '');
            $.historyLoad(hash);
            return false;
        });
    },
    // Register global ajax callbacks
    registerAjaxCallbacks: function(){
        $('span.notifier').hide()
            .ajaxStart(function(){
                var msg = $.sme.ajaxStart || '正在加载, 稍后';
                $('span.notifier').attr('class', 'notifier load').text(msg).show();
            }).ajaxError($.sme.cbk.ajaxError);
    },
    // Justift Paginator
    justifyPainator: function(){
        $('div.paging a:empty').remove();
    },
    // Initialize widgets, from app/views/posts/add.ctp
    initWidgets: function(){
        // Bind widget hover actions
        $('div.widget').hover(function(){
            $(this).children('div.toggle').addClass('hover');
        }, function(){
            $(this).children('div.toggle').removeClass('hover');
        });
        // Bind widget toggler actions
        $('div.widget div.toggle').click(function(){
            $(this).nextAll('div.content').slideToggle(200);
        });
    },
    // Justify table headers for translation
    justifyTables: function(){
        $('th:contains(Workplace)').text('工作地点');
        $('th:contains(Clicks)').text('点击量');
        $('th:contains(Company)').text('所属公司');
        $('#table_jobs th:contains(Students Job Count)').text('申请人数');
        $('#table_posts th:contains(Comment Count)').text('Comment');
    },
    // Justify external links
    justifyLinks: function(){
        $('a.external').html('&nbsp;').attr('target', '_blank');
        $('a[rel=external]').attr('target', '_blank');
        $('a[rev=external]').attr('target', '_blank');
    },
    // Justify text input fields
    justifyInputs: function(){
        /* set all auto complete off */
        $('input.text').attr('autocomplete', 'off');
    },
    // Notify users of server side session flash messages
    flashMessage: function(){
        var elm = $('#flashMessage'), text = elm.text();
        if(elm.length && (text != '')){
            elm.remove();
            $.sme.fn.notify('notice', text);
        }
        var elm = $('#authMessage'), text = elm.text();
        if(elm.length && (text != '')){
            elm.remove();
            var type = 'notice';
            if(text.indexOf('对不起') >= 0){
                type = 'error';
            }
            $.sme.fn.notify(type, text);
        }
    },
    /* Init tooptips for all <a, li, span> element */
    tooltips: function(){
        /* Home page Post tooltip */
        var options = {
            position: 'center center',
            offset: [110, 200],
            tip: '#abstract',
            lazy: false,
            effect: 'slide'
        };
        var right = {
            right: {
                direction: 'down',
                bounce: true
            }
        };
        var left = {
            left: {
                direction: 'down',
                bounce: true
            }
        };
        /*$('#latest_posts a[title]')
            .tooltip(options)
            .dynamic(right);
        $('#latest_companies a[title]')
            .tooltip($.extend(options, {offset: [110, -50]}))
            .dynamic(right);
        $('#latest_jobs a[title]')
            .tooltip($.extend(options, {offset: [60, -50]}))
            .dynamic(left);
        $('table.fixed th.checkbox, table.fixed td a[title], div.view a[title]')
            .tooltip($.extend(options, {
                position: 'center right',
                offset: [20, -5],
                tip: '#tooltip'
            })).dynamic(left);*/
        var options = $.extend(options, {position: 'center bottom', tip: '#tooltip'});
        $('a#bug').tooltip($.extend(options, {offset: [100, 80]})).dynamic(left);
        $('a#help').tooltip($.extend(options, {offset: [57, -130]})).dynamic(left);
        $('a#login').tooltip($.extend(options, {offset: [58, -250]})).dynamic(left);
        $('a#home').tooltip($.extend(options, {offset: [10, 15]})).dynamic(right);
    },
    /* fetch elements for dialogs */
    dialogs: function(){
        $.sme.dialog = {
            trash: $('#dialog_data_delete')
        };
    }
});

// User interactive callbacks
$.extend($.sme.cbk, {
    // Ajax start notification
    ajaxStart: function(content){
        var content = content || $.sme.ajaxStart || '正在加载, 稍后';
        $.sme.notify('load', content);
    },
    // Ajax success callback
    ajaxSuccess: function(content){
        var content = content || '设置已保存';
        $.sme.notify('success', content);
    },
    // Ajax error callback
    ajaxError: function(content){
        var content = content || '糟糕, 请求出错啦';
        $.sme.notify('error', content);
    },
    // New callback for Ajax History Page Loading
    ajaxMenuItemLoad: function(hash){
        if(hash){
            if($.browser.msie){
                hash = encodeURIComponent(hash);
            }
            if($.sme.data.hash == hash){
                $.log('Current Page is loaded and visible, just return');
                return false;
            }
            $.sme.data.hash = hash;
            $.log('Loading ajax history page #'+hash);
            $.ajax({
                global: false,
                url: hash,
                complete: $.sme.cbk.ajaxMenuItemLoadComplete
            });
        }
    },
    // Ajax tab load complete callbacks
    ajaxMenuItemLoadComplete: function(xhr){
        $('#column_right').html(xhr.responseText);
    },
    /* Ajax check for unique fields */
    ajaxCheck: function(){
        /* this[options] = {
                label: the label for message display
                input: the field to be checked for
                id: input id to check for fields
                model: Server side model name
                fielden: Database table field name
                fieldzh: field name in Chinese
                control: Data cacke key such as: post_term, company_type
        */
        if(this.input.attr('id') == this.id){
            var value = this.input.val(), data = {},
                label = this.label, fieldzh = this.fieldzh, fielden = this.fielden,
                control = this.control, model = this.model;
            data[this.fielden] = value;
            if(value != $.sme.data[this.control]){
                $.log('Check for '+model+'.'+fielden+' with #'+value);
                $.sme.data[this.control] = value;
                $.ajax($.extend($.sme.option.json, {
                    global: false,
                    data: $.sme.datas(data, this.model),
                    url: $.sme.url[this.control]('check'),
                    beforeSend: function(){
                        label.addClass('load').html('检查'+fieldzh+', 稍后').nextAll('label.success').remove();
                    },
                    success: function(json){
                        $.sme.status[control] = json.status;
                        if(json.status){
                            $.log(model+'.'+fielden+'('+value+') not taken, useable');
                            label.attr('class', 'success').attr('id', $.time())
                                .html(fieldzh+'<strong>'+$.sme.data[control]+'</strong>可用')
                                .prev('input').addClass('success');
                        }else{
                            $.log(model+'.'+fielden+'('+value+') taken, please choose another');
                            label.attr('class', 'error')
                                .html(fieldzh+'<strong>'+$.sme.data[control]+'</strong>已存在')
                                .prev('input').addClass('error');
                        }
                    }
                }));
            }else{
                label.remove();
            }
        }else{
            label.remove();
        }
    },
    /* Apply for a job via ajax request */
    ajaxApply: function(event){
        $.sme.ajaxStart = '正在处理您的请求, 稍后';
        $.sme.json.apply(this, [event]);
    },
    /* Delete job application using ajax request */
    ajaxAntiApply: function(event){
        $.sme.ajaxStart = '正在取消职位申请, 请稍后';
        $.sme.json.apply(this, [event, function(json){
            if(json.status){
                this.remove();
            }
        }]);
    },
    /* Delete a data record via ajax request */
    ajaxDelete: function(event){
        //if(!window.confirm('确定要删除该数据及其相关记录么?')) return false;
        event.preventDefault();
        var link = $(this);
        $.sme.cbk.dialog('trash', function(){
            $(this).dialog('close');
            $.sme.ajaxStart = '正在删除数据及其相关信息, 稍后';
            $.sme.json.apply(link, [event, function(json){
                if(json.status){
                    this.parents('tr').fadeOut(2000, function(){
                        $(this).remove();
                    });
                }
            }]);
        });
        $.sme.dialog.trash.dialog('open');
    },
    /* Ajax view or edit */
    ajaxView: function(event){
        event.preventDefault();
        var key = $(this).data('ajax');
        //$.log('clicked #' + $(this).parents('table').attr('id'));
        if($.sme.data[key] == this.href) return false;
        $.sme.data[key] = this.href;
        $.sme.html(this.href, key);
    },
    /* Switch on or off toggable fields */
    ajaxSwitchOn: function(event){
        $.sme.ajaxStart = '正在保存更改, 稍后';
        $.sme.json.apply(this, [event, function(json){
            if(json.status){
                this.parent('span').hide().next('span:hidden').show();
            }
        }]);
    },
    ajaxSwitchOff: function(event){
        $.sme.ajaxStart = '正在保存更改, 稍后';
        $.sme.json.apply(this, [event, function(json){
            if(json.status){
                this.parent('span').hide().prev('span:hidden').show();
            }
        }]);
    },
    /* Init User menus, from app/views/elements/menu_user_admin.ctp; */
    initUserMenu: function(){
        // Cookie support on revision 58
        // Hide All Subment list on page initialze
        $('div.submenu').hide();
        // Add hover actions for toggle divisions
        $('ul.menu li.item:has(div.submenu)').hover(function(){
            $(this).children('div.toggle').addClass('hover');
        }, function(){
            $(this).children('div.toggle').removeClass('hover');
        });
        // Add click actions for toggle divisions
        $('div.toggle').click(function(){
            $(this).nextAll('div.submenu').slideToggle(150);
        });
        /* Perfect menu item match */
        var path = window.location.pathname,
            id = $('ul.menu').attr('id').replace('menu_', ''),
            menu = $.sme.menu[id], current = currentItem = false;
        $.log(window.location);
        $.each(menu, function(parent, value){
            $.each(value, function(index, item){
                if(path.indexOf(item) >= 0){
                    current = parent;
                    currentItem = item;
                    return false;
                }
            });
            if(current){
                return false;
            }
        });
        $.log('Perfect match: #'+current+'.'+currentItem);
        /* Show some one that matches current location hash */
        var currentMenu = $('li#'+current).addClass('current');
        $('div.submenu', currentMenu).show();
        $('li:has(a[href='+path+'])', currentMenu).addClass('current');
    },
    /* Initialize CKEditor instance for elements */
    initCKEditor: function(id, toolbar, finder){
        if(!$('#'+id).length) return false;
        if(!CKEDITOR){ return false; }
        var toolbar = toolbar || 'ckeditor', finder = finder || false;
        $.log('Init CKEditor for field #'+id);
        var editor = CKEDITOR.replace(id, $.sme.option[toolbar]);
        if(finder && CKFinder){
            CKFinder.SetupCKEditor(editor, $.sme.CKFinderPath);
        }
    },
    /* Initialize rich text editor on user specified */
    initBasicEditor: function(){
        var id = $(this).parent('p').next('textarea').attr('id');
        $.sme.cbk.initCKEditor(id, 'basic');
        $(this).remove();
    },
    /* IndexPage action division togglers */
    showActions: function(){
        $('p.actions', this).css('visibility', 'visible');
    },
    hideActions: function(){
        $('p.actions', this).css('visibility', 'hidden');
    },
    /* Justify datetime inputs */
    datepicker: function(){
        $('div.datetime').each(function(){
            var div = $(this), clone = div.clone().empty();
            clone.append(div.children('label'));
            div.children('select').each(function(){
                var select = $(this);
                $('<input type="hidden"/>').attr({
                    name: select.attr('name'),
                    id: select.attr('id'),
                    value: select.val()
                }).appendTo(clone);
            });
            clone.append('<input class="datepicker input text" type="text"/>').insertAfter(div);
            div.remove();
        });
        $('.datepicker').datepicker({
            dateFormat: 'yy-mm-dd',
            buttonImage: $.sme.url.base+'/img/calendar.png',
            buttonImageOnly: true,
            duration: '',
            buttonText: '选择日期',
            showOn: 'button',
            showAnim: 'fadeIn',
            onSelect: function(sel_date) {
                var newDate = sel_date.split('-');
                $(this).siblings('input').each(function(){
                    id = $(this).attr('id');
                    if (id.substring(id.length-3, id.length)=='Day') $(this).val(newDate[2]);
                    else if (id.substring(id.length-5, id.length)=='Month') $(this).val(newDate[1]);
                    else if (id.substring(id.length-4, id.length)=='Year') $(this).val(newDate[0]);
                });
            },
            beforeShow: function() {
                var year = month = day = id = '';
                $(this).siblings('input').each(function() {
                    id = $(this).attr('id');
                    if (id.substring(id.length-3, id.length)=='Day') day = $(this).val();
                    else if (id.substring(id.length-5, id.length)=='Month') month = $(this).val();
                    else if (id.substring(id.length-4, id.length)=='Year') year = $(this).val();
                });
                $(this).val(year+'-'+month+'-'+day);
                return {};
            }
        });
    },
    /* init an dialogue */
    dialog: function(name, callback){
        if(!$.sme.dialog[name]) return false;
        $.log('init dialog for '+name);
        $.sme.dialog[name].dialog($.extend($.sme.option.dialog, {
            buttons: {
                "确定": callback || function(){},
                "取消": function(){
                    $(this).dialog("close");
                }
            }
        }));
    }
});

// Utility functions
$.extend($.sme.fn, {
    // System message boadcast system for ajax activities, form validations
    notify: function(type, msg){
        var span = $('span.notifier').attr('class', 'notifier '+type).text(msg);
        var left = ($('#header').width() - span.width())/2 + 'px';
        span.css({position: 'fixed', left: left}).fadeIn(500, function(){
                setTimeout(function(){
                    span.fadeOut();
                }, 3000);
            });
    },
     // Auto notify, this is usally used when an json request complete
    autoNotify: function(json){
        $.sme.cbk[json.status ? 'ajaxSuccess' : 'ajaxError'](json.code);
    },
    // Handles json requests and responders
    json: function(event, callback){
        event.preventDefault();
        var link = $(this), callback = $.isFunction(callback) ? callback : $.sme.k;
        $.ajax($.extend($.sme.option.json, {
            type: 'get',
            url: link.attr('href'),
            success: function(json){
                $.sme.autoNotify(json);
                $.log(json);
                callback.apply(link, [json]);
            }
        }));
    },
    // Handle all html content requests
    html: function(url, element){
        $(element).load(url, null, function(){
            $('span.notifier').hide();
        });
    },
    // Process data as CakePHP firendly format
    datas: function(object, model){
        var data = {};
        var model = model || 'User';
        for(var index in object){
            data['data['+model+']['+index+']'] = object[index];
        }
        return data;
    }
});

// Global options
$.extend($.sme.option, {
    html: {
        type: 'get',
        global: true,
        dataType: 'html'
    },
    json: {
        type: 'post',
        global: true,
        dataType: 'json'
    },
    ckeditor: {
        language: 'zh-cn',
        resize_enabled: false,
        height: 500,
        toolbar: [
            ['Source','-','Save','NewPage','Preview', '-', 'Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock', '-', 'Maximize', 'ShowBlocks','-','About'],
            ['Link','Unlink','Anchor', '-', 'Image','Table','HorizontalRule'],
            ['Bold','Italic','Underline','Strike', '-','NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            '/',
            ['Styles','Format','Font','FontSize', '-','TextColor','BGColor','-']
        ]
    },
    basic: {
        language: 'zh-cn',
        resize_enabled: false,
        toolbar: 'Basic'
    },
    dialog: {
        autoOpen: false,
        modal: true,
        width: 300,
        maxWidth: 300,
        minWidth: 240,
        maxHeight: 180,
        minHeight: 150,
        position: "center"
    }
});

$.extend($.sme, $.sme.fn);

/* Website menu system */
$.sme.menu = {
    root: {
        dashboard: ['dashboard'],
        search: ['search'],
        posts: ['posts', 'post_terms'],
        comments: ['comments'],
        companies: ['companies', 'company_industries', 'company_locations', 'company_types'],
        jobs: ['jobs'],
        tools: ['students/import', 'students/export'],
        students: ['students', 'student_resumes'],
        users: ['users', 'groups', 'actions', 'options']
    },
    teacher: {
        dashboard: ['dashboard'],
        search: ['search'],
        posts: ['posts', 'post_terms'],
        comments: ['comments'],
        companies: ['companies', 'company_industries', 'company_locations', 'company_types'],
        jobs: ['jobs'],
        tools: ['students/export'],
        students: ['students', 'student_resumes'],
        users: ['users/password', 'users/config', 'options']
    },
    student: {
        dashboard: ['users/dashboard'],
        search: ['search'],
        posts: ['posts/home'],
        jobs: ['jobs', 'companies', 'students/job'],
        students: ['students', 'student_resumes'],
        users: ['users/password', 'users/config']
    }
};

})(jQuery);